<?php

namespace App\Repositories\Api;

use App\Http\Services\LoginService;
use App\Models\AccountRecord;
use App\Models\ChsiCheck;
use App\Models\Config;
use App\Models\Enlist;
use App\Models\Income;
use App\Models\Member;
use App\Models\MemberRecommend;
use App\Models\MemberVisit;
use App\Repositories\DictIpRepository;
use App\Repositories\PictureMappingRepository;
use Cache;
use Exception;

class   MemberRepository
{
    /**
     * 用户登录
     * @param string $phone
     * @param string $password
     * @return bool
     * @throws Exception
     */
    public function adminLogin($unionid = "", $openid = "")
    {
        if (!$unionid && !$openid)
            throw new Exception("unionid 解析错误，请重新解析", 1);

        if ($unionid) {
            $member = Member::query()->where("unionid", $unionid)->first();
        } else {
            $member = Member::query()->where("weapp_openid", $openid)->first();
        }
        if (empty($member)) return null;
        $loginService = new LoginService();
        $token = $loginService->authcode($member['id'], 'ENCODE');

        return [
            "id" => $member['id'],
            'gender' => $member['gender'],
            "username" => $member['username'],
            "avatar" => $member['avatar'],
            "cancel" => $member['cancel'],
            "is_subscribe" => $member["is_subscribe"],
            "lcity" => $member['lcity'],
            "token" => $token,
            "id_code" => md6($member['id'])
        ];
    }

    public function getIdByToken($token = "")
    {
        if (!$token) return "";
        $login = new LoginService();
        $adminId = $login->authcode($token, 'DECODE');
        return $adminId;
    }

    /**
     * 更新信息
     */
    public function updateFields($id, $data = [])
    {
        if (!$id) {
            throw new Exception("会员不存在");
        }
        delRedis("member_" . md5($id), 2); //删除缓存
        return Member::query()->where("id", "=", $id)->update($data);
    }

    public function saveOrUpdate($data = [], $uid = 0)
    {
        if ($uid) {
            delRedis("member_" . md5($uid), 2); //删除缓存
            return Member::where("id", "=", $uid)->update($data);
        } else {
            return Member::create($data);
        }
    }

    public function getAdminInfo($id)
    {
        if (!intval($id)) return "";
        $cache_key = "cache_member_" . md5($id);
        $res = Cache::get($cache_key);
        if (env("OPEN_CACHE") && $res) return $res;

        $res = Member::where("id", "=", $id)->first();
        if (!$res) return "";

        $res['avatar'] && $res['avatar_preview'] = getPreviewImage($res['avatar']);
        $res['weixin_qrcode_pic'] && $res['weixin_qrcode_pic_preview'] = getPreviewImage($res['weixin_qrcode_pic']);
        $res['work_auth_pic'] && $res['work_auth_pic_preview'] = getPreviewImage($res['work_auth_pic_pic']);

        $res['idcard_type_title'] = idcard_type($res['idcard_type']);
        $res['idcard_status_title'] = member_idcard_status($res['idcard_status']);
        if (!empty($res['education_type'])) {
            $res['education_type_title'] = education_type($res['education_type'])['name'];
        } else {
            $res['education_type_title'] = "";
        }
        $res['gender_title'] = member_gender($res['gender']);
        $res['ismyself_title'] = intval($res['ismyself']) == 0 ? "" : ismyself($res['ismyself']);
        $res['status_title'] = com_status($res['status']);
//        $res['country_title'] = Member::getMobilerea($res['mobile']);
        $res['last_login_ip_title'] = (new DictIpRepository())->getIpRegion($res['last_login_ip']);

        $res['last_login_time'] = date("Y-m-d H:i:s", $res['last_login_time']);

        $pictures = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $res['id'],
            'object_type' => "member"
        ]);

        $res['total_account'] = bcadd(floatval(str_replace(',', '', $res['account'])), floatval($res['account_temp']), 1);

        if (strtotime($res['birthday']) <= 0) {
            $res['birthday'] = "";
        }

        $res['pictures'] = $pictures ?? [];
        $res['id_code'] = md6($res['id']);

        if ($res['status'] == 1) {
            Cache::set($cache_key, $res);
        }
        return $res;
    }

    /**
     * 应征会员信息
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-11T20:07:59+0800
     * @param    [type]                   $id     [description]
     * @return   [type]                           [description]
     */
    public function getEnlistMember($id)
    {
        $res = $this->getOne($id);
        if (!$res) return "";
        //应征
        $enlist = Enlist::where(['enlist_uid' => UID, 'enlisted_uid' => $id])->first();
        //被应征
        $enlisted = Enlist::where(['enlisted_uid' => UID, 'enlist_uid' => $id])->first();
        $res['is_enlist'] = $enlist ? 1 : ($enlisted ? 2 : 0);
        $res['enlist'] = $enlist ?? $enlisted;

        return $res;
    }

    public function getByUnionid($unionid = "")
    {
        if (empty($unionid)) return "";
        $member = Member::where("unionid", "=", $unionid)->first();
        if (empty($member)) return "";
        $member['pictures'] = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $member['id'],
            'object_type' => "member"
        ]);

        return $member;
    }

    public function getOne($id = 0)
    {
        if (!intval($id)) return NULL;

        $cache_key = "member_" . md5($id);
        $member = getRedisByKey($cache_key, 2);

        if (env("OPEN_CACHE") && $member)
            return $member;

        $member = Member::query()->where("id", "=", $id)->first();
        if (!$member) return NULL;

        $member['pictures'] = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $member['id'],
            'object_type' => "member"
        ]);

        if (strtotime($member['birthday']) <= 0) {
            $member['birthday'] = NULL;
        }

        //!empty($member['birthday']) && $member['birthday'] = substr($member['birthday'], 0, 7);
        $member['id_code'] = md6($member['id']);
        if ($member['status'] == 1) {
            setRedisByDb($cache_key, $member, 0, 2);
        }

        return $member;
    }

    public function getSimpleMember($id = 0, $type = 1, $show_contact = false)
    {
        $fields = [
            1 => ["id", "username", "avatar", "idcard_status", "status", "award_type"],
            //互选池 详情页
            2 => ["id", "avatar", 'account', 'account_temp', "avatar_status", "username", "height", "birthday", "last_login_time", "gender", "hometown", "location", "residence", "education", "undergraduate", "master_college", "profession", "occupation", "status", "idcard_status", "current_status", "ldistrict", "Longitude", "Latitude", "lcity", "cancel"],
            //附近的人 详情页
            3 => ["id", "avatar", 'account', 'account_temp', "avatar_status", "height", "birthday", "username", "gender", "status", "idcard_status", "current_status", "Longitude", "Latitude", "lcity", "cancel", "location_city"],
        ];

        $field = $fields[$type];
        $cache_key = "cache_member_" . md5($id . '-' . $type);

        $res = Cache::get($cache_key);
        if (env("OPEN_CACHE") && $res) return $res;

        //去除联系方式
        if ($show_contact) {
            $field[] = 'weixin';
            $field[] = 'weixin_qrcode_pic';
        }
        $res = Member::where("id", "=", $id)->first(!empty($field) ? $field : "*");

        if (isset($res['account']))
            $res['account'] = number_format(str_replace(',', '', $res['account']), 2);
        if (isset($res['account_temp']))
            $res['account_temp'] = number_format($res['account_temp'], 2);

        if (!empty($res->combo) && $res->combo->end_time > date("Y-m-d")) {
            $res['is_vip'] = 1;
        } else {
            $res['is_vip'] = 0;
        }
        $res['status_title'] = com_status($res['status']);

        if (in_array($type, [2, 3])) {
            $res['total_account'] = bcadd(floatval(str_replace(',', '', $res['account'])), floatval($res['account_temp']), 2);
        }

        if ($res['status'] == 1 && env("OPEN_CACHE")) {
            Cache::set($cache_key, $res);
        }

        return $res;
    }

    /*public function getMemberCategory($v = '')
    {
        $model_set_fields = array(
            array('title' => "头像", "id" => 12, 'type' => "image", 'fields' => array('avatar'), 'hideTitle' => true, 'link' => "/pages/member/info/edit_avatar"),
            array('title' => "个人相册", "id" => 6, 'type' => "pictures"),
            array('title' => "认证信息", "id" => 14, 'fields' => array('idcard_status', 'status', 'country'), 'link' => "/pages/member/auth_idcard/index"),
            array('title' => "基本信息", "id" => 1, 'fields' => array('username', 'gender', 'birthday', 'height', 'marital_history', 'make_friend_type')),
            array('title' => "联系方式", "id" => 3, 'fields' => array('mobile', 'weixin', 'qq', 'weixin_qrcode_pic')),
            array('title' => "学校", "id" => 4, 'fields' => array('undergraduate', 'master_college', 'current_status', 'education', 'profession')),// 'doctor_college',
            array('title' => "工作", "id" => 5, 'fields' => array('work_org', 'work_status', 'occupation', 'work_type', 'year_salary')),
            array('title' => "家庭情况", "id" => 8, 'fields' => array('famliy_condition')),
            array('title' => "自我介绍", "id" => 9, 'fields' => array('about_me', 'hobby')),
            array('title' => "心仪的Ta", "id" => 7, 'fields' => array('about_you')),
            array('title' => "实名认证", "id" => 11, 'type' => "picture", 'link' => "/pages/member/auth_idcard/index"),
            array('title' => "本科学历认证", "id" => 10, 'type' => "picture", 'fields' => array('status', 'idcard_type', 'undergraduate', 'education_pic'), 'link' => "/pages/member/auth_education/index", 'hideTitle' => true),//身份证照片
        );

        return isset($model_set_fields[$v]) ? $model_set_fields[$v] : $model_set_fields;
    }*/

    public function getMemberQuickFields()
    {
        return [
            "gender" => array("title" => "性别", "required" => true, "type" => "select", 'range_key' => "title", 'options' => [['title' => "未知", 'id' => 'U'], ['title' => "男", 'id' => 'M'], ['title' => "女", 'id' => 'F']], 'tip' => "注意：性别只能修改一次。认证后不能修改，如需修改联系`玉兔助手`或提交问题反馈"),
            "avatar" => array("title" => "头像", "required" => true, "type" => "image"),
            "username" => array("title" => "昵称", "required" => true, 'tip' => "此处禁止透露联系方式，被发现扣爱心！", 'type' => "nickname"),
            "birthday" => array("title" => "出生日期", "required" => true, 'type' => "date", 'tip' => "出生日期按身份证出生日期填写，如果实际与身份证不一致，可在自我介绍里面说明。"),
            "height" => array("title" => "身高", "required" => true, "type" => "select", 'options' => member_height(), 'default_val' => 0),

            "occupation" => array("title" => "职业", "required" => true, 'type' => "mutilSelect"),
            "make_friend_type" => array("title" => "交友类型", "required" => true, "type" => "select", 'options' => friend_type()),
            "hometown" => array("title" => "家乡", "required" => true, 'type' => "address", 'tip' => "省市县写全，具体到县或区，如安徽安庆怀宁",),
            "location" => array("title" => "现居城市", "required" => true, 'type' => "address", 'tip' => "如江苏苏州，此处不要写具体的居住地点",),

            "weixin" => array("title" => "微信号", "required" => true, 'tip' => "务必在设置隐私添加我的方式里开启微信号查找"),
            "mobile" => array("title" => "手机号码", "required" => true, 'tip' => "手机号仅作为紧急联系人，不会暴露给任何用户"),

            "current_status" => array("title" => "目前状态", "required" => true, "type" => "select", 'options' => current_status(), 'tip' => "本科在读->硕士在读->博士在读->工作只能上升修改，不能下降，一旦修改无法改回，会影响平台功能使用。请严格按当前实际情况填写，不要随意改，即使退出也不要胡乱改，因为你不确定什么时候还会再回来。在职读研/博的不算在校生。", 'showEditTip' => true),
            "year_salary" => array("title" => "年收入", "required" => true, "type" => "select", 'options' => salary_status(),),
            "education" => array("title" => "最高学历", "required" => true, "type" => "select", 'options' => edu_status()),
            "undergraduate" => array("title" => "本科学校", "required" => true, 'tip' => "可输入学校名前面一两个字或者简称，系统会自动弹出相关学校选中即可。请严格按毕业证学校名称填全名，非统招注明学历类型"),
            "master_college" => array("title" => "最高学历学校", 'tip' => "没有硕士学校的不填，直接点确定进入下一步。可输入学校名前面一两个字或者简称，系统会自动弹出相关学校选中即可。请严格按毕业证学校名称填全名。"),

            "pictures" => array("title" => "个人相册", "required" => true, 'type' => "pictures", 'tip' => "此处禁止透露联系方式，一旦发现将按照《处罚规则》处罚！"),

            "work_org" => array("title" => "工作单位", "required" => true, 'tip' => "写全最好，也可以半模糊处理"),
            "work_status" => array("title" => "工作状况", "required" => true, "type" => "select", 'options' => work_status(),),
            "work_type" => array("title" => "单位类型", "required" => true, "type" => "select", 'options' => company_status()),

            "work_or_study_place" => array("title" => "上班地点", "required" => true, 'type' => "text", 'tip' => "写地标或地铁站，在校生写无，不要包含城市名",),
            "residence" => array("title" => "居住地点", "required" => true, 'type' => "text", 'tip' => "写地标或地铁站，在校生写校区，此处不要包含现居城市",),
            "marital_history" => array("title" => "婚姻状况", "required" => true, "type" => "select", 'options' => marriage_status(), 'tip' => "非未婚选未婚被投诉核实将封号！", 'showEditTip' => true),

            "famliy_condition" => array("title" => "家庭情况", "required" => true, "type" => "textarea", 'placeholder' => "", 'tip' => "介绍一下父母职业，兄弟姐妹，比如普通家庭、经商家庭、高职家庭"),
            "profession" => array("title" => "专业", "required" => true, 'tip' => "输入专业前面一两个字系统会弹出相关专业选中即可。本硕博专业不一致的可以斜杠分隔。"),
            "about_me" => array("title" => "自我介绍", "required" => true, 'tip' => '介绍下自己的性格、习惯、优点、缺点(请认真填写，乱填会被举报封禁的哟)', "type" => "textarea", 'placeholder' => "至少20个字"),
            "hobby" => array("title" => "兴趣爱好", "required" => true, 'tip' => '业余喜欢做什么，比如：喜欢看什么样的书、喜欢去什么样的地方旅游等', "type" => "textarea", 'placeholder' => ""),
            "about_you" => array("title" => "心仪的Ta", "required" => true, 'tip' => '说出你对另一半的期许', "type" => "textarea", 'placeholder' => ""),

            "weixin_qrcode_pic" => array("title" => "微信二维码", "type" => "image", "required" => true, 'tip' => "系统暂时只支持识别黑色前景白色背景的微信二维码。彩色背景二维码将无法保存！"),
        ];
    }

    public function getMemberFields()
    {
        $fields = array(
            "avatar" => array("title" => "头像", "required" => true, "type" => "image", 'hideTitle' => true),
            "username" => array("title" => "昵称", "required" => true, 'type' => 'nickname', 'tip' => "此处禁止透露联系方式，被发现扣爱心！",),
            "gender" => array("title" => "性别", "required" => true, "type" => "select", 'default_val' => 0, 'options' => [['U', "未知"], ['F', "女"], ['M', "男"]], 'default_val' => 1, 'range_key' => 1, 'tip' => "注意：性别只有一次重新设置机会，当前正确的禁止修改。修改一旦保存无法自行改回！", 'showEditTip' => true, "focus" => true),
            "mobile" => array("title" => "手机号码", "required" => true, 'is_hide' => true,),
            "weight" => array("title" => "体重", 'tip' => "单位公斤"),
            "height" => array("title" => "身高", "required" => true, "type" => "select", 'options' => member_height(), 'default_val' => 0),

            "qq" => array("title" => "备用微信号", "required" => false, 'placeholder' => "和微信绑定能搜到微信的qq号"),
            "birthday" => array("title" => "出生日期", "required" => true, 'type' => "date", 'tip' => "出生日期按身份证出生日期填写，如果实际与身份证不一致，可在自我介绍里面说明。"),
            "weixin" => array("title" => "微信号", "required" => true, 'tip' => "务必在设置隐私添加我的方式里开启微信号查找"),
            "weixin_qrcode_pic" => array("title" => "微信二维码", "type" => "image", "required" => true, 'tip' => "系统暂时只支持识别黑色前景白色背景的微信二维码。彩色背景二维码将无法保存！"),
            "work_org" => array("title" => "工作单位", "required" => true, 'tip' => "写全最好，也可以半模糊处理"),
            "work_status" => array("title" => "工作状况", "required" => true, "type" => "select", 'options' => work_status(),),
            "balance" => array("title" => "账户余额", 'default_value' => "0.00"),
            "work_type" => array("title" => "单位类型", "required" => true, "type" => "select", 'options' => company_status(),),
            "hometown" => array("title" => "家乡", "required" => true, 'type' => "address", 'tip' => "如选择器里没有，请在下输入框方手动输入",),
            "location" => array("title" => "现居城市", "required" => true, 'type' => "address", 'tip' => "海外城市请在下输入框方手动输入",),
            "jw_location" => array("title" => "距你", "required" => true, 'type' => "location", 'tip' => "如上海，此处不要写具体的居住地点",),

            "work_or_study_place" => array("title" => "上班地点", "required" => true, 'type' => "text", 'tip' => "上班族填上班地或附近地标或地铁站名，在校生写无。不允许包含城市名，若必须包含城市名，城市名中间加空格保存即可。",),
            "residence" => array("title" => "居住地点", "required" => true, 'type' => "text", 'tip' => "上班族填居住地或附近地标或地铁站名，在校生写校区。不允许包含城市名，若必须包含城市名，城市名中间加空格保存即可。",),
            "education" => array("title" => "最高学历", "required" => true, "type" => "select", 'options' => ["", "博", "硕", "本", "专"],),
            "year_salary" => array("title" => "年收入", "required" => true, "type" => "select", 'options' => salary_status(),),
            "marital_history" => array("title" => "婚姻状况", "required" => true, "type" => "select", 'options' => marriage_status(), 'tip' => "非未婚选未婚被投诉核实将封号！", 'showEditTip' => true),

//            "goufang_condition" => array("title" => "住房情况", "required" => true, "type" => "select", 'options' => house_status(), ),
            "famliy_condition" => array("title" => "家庭情况", "required" => true, "type" => "textarea", 'placeholder' => "父母职业及兄弟姐妹排行情况，告诉对方你的家庭情况是彼此了解很重要的一步哦"),
            "current_status" => array("title" => "目前状态", "required" => true, "type" => "select", 'options' => current_status(), 'tip' => "目前状态只能往上修改不能往下修改，一旦修改无法自行改回。请严格按当前实际情况填写，不要随意改。即使退出也不要胡乱改，因为你不确定什么时候还会再回来。在职读研/博的请按工作选择状态。", 'showEditTip' => true),

            "undergraduate" => array("title" => "本科学校", "required" => true, 'tip' => "可输入学校名前面一两个字或者简称，系统会自动弹出相关学校选中即可。请严格按毕业证学校名称填全名，非统招注明学历类型"),
            "master_college" => array("title" => "最高学历学校", "required" => true, 'tip' => "最高学历为本科，可与本科一样，请严格按毕业证学校名称填全名。"),
//            "doctor_college" => array("title" => "博士学校全称", 'tip' => "没有博士学校的不填，直接点确定进入下一步。可输入学校名前面一两个字或者简称，系统会自动弹出相关学校选中即可。请严格按毕业证学校名称填全名。"),

            "profession" => array("title" => "专业", "required" => true, 'tip' => "输入专业前面一两个字系统会弹出相关专业选中即可。本硕博专业不一致的可以斜杠分隔。"),
            "occupation" => array("title" => "职业", "required" => true, 'type' => "mutilSelect"),
            "about_me" => array("title" => "自我介绍", "required" => true, "type" => "textarea", 'tip' => '请填写自我介绍，不少于20字。少于20个字，此提醒将重复出现！', 'placeholder' => "关于自己，还有些什么想说的呢？如兴趣爱好，个性特点，业余时间喜欢做些什么，未来规划等等。在校生要明确哪年(不要写明年或后年，写21年或22年）毕业以及毕业以后想去哪发展。非本人的务必在此说清楚和本人的关系！不要手动加过多换行符！\r【注意】个人资料里除联系方式一栏其它任何地方禁止以任何形式透漏联系方式，发现或被投诉扣账户余额，账户余额被扣成负的充值后才能使用网站！"),
            "about_you" => array("title" => "心仪的Ta", "required" => true, "type" => "textarea", 'tip' => '请填写心仪的Ta，不少于15字。少于15个字，此提醒将重复出现！', 'placeholder' => "想对ta说些什么呢？出生年份范围年龄、身高范围、学历、职业/专业、工作/在读等方面有些什么要求呢？是否接受异地，接受的话能接受哪些城市的呢？\r不要手动加过多换行符！\r【注意】个人资料里除联系方式一栏其它任何地方禁止以任何形式透漏联系方式，发现或被投诉扣账户余额，账户余额被扣成负的充值后才能使用网站！"),

            "make_friend_type" => array("title" => "交友类型", "required" => true, "type" => "select", 'options' => friend_type(),),
            "id_front_pic" => array("title" => "实名认证材料", "type" => "image",),

            "education_pic" => array("title" => "学历证书", "type" => "image",),
            "status" => array("title" => "本科学历", "type" => "radio", 'default_value' => 0, 'options' => com_status(), "tip" => "审核要求：高考统招本科或国外同等学历，其它情况不符合审核要求，但不影响使用平台。"),
            "country" => array("title" => "手机号归属地", "required" => true, "class" => "span3",),
            "hobby" => array("title" => "兴趣爱好", "required" => true, 'tip' => '请填写自我介绍，不少于20字。少于20个字，此提醒将重复出现！', "type" => "textarea", 'placeholder' => "关于自己，还有些什么想说的呢？如兴趣爱好，个性特点，业余时间喜欢做些什么，未来规划等等。在校生要明确哪年(不要写明年或后年，写21年或22年）毕业以及毕业以后想去哪发展。非本人的务必在此说清楚和本人的关系！不要手动加过多换行符！\r【注意】个人资料里除联系方式一栏其它任何地方禁止以任何形式透漏联系方式，发现或被投诉扣账户余额，账户余额被扣成负的充值后才能使用网站！"),
            "last_login_ip_title" => array("title" => "IP属地", "required" => true, "class" => "span3",),
            "idcard_status" => array("title" => "实名", "required" => true, "type" => "select", 'options' => member_idcard_status(), "tip" => "审核要求：高考统招本科或国外同等学历，其它情况不符合审核要求，但不影响使用平台。"),
            "idcard_type" => array("title" => "认证方式", "required" => true, "type" => "select", 'options' => education_type_demo(),),
        );

        return $fields;
    }

    //用于用户解锁联系方式页面
    public function getMemberCategoryForMember($extra_ids = "")
    {
        $model_set_fields = array(
            ['title' => "头像", "id" => 12, 'type' => "picture", 'fields' => ['avatar']],
            ['title' => "认证信息", "id" => 14, 'fields' => array('status', 'idcard_status')],
            ['title' => "联系方式", "id" => 3, 'fields' => array('mobile', 'weixin', 'weixin_qrcode_pic')],
            ['title' => "基本信息", "id" => 1, 'fields' => array('username', 'gender', 'birthday', 'height', 'marital_history', 'make_friend_type', 'hometown', 'location', 'work_or_study_place', 'residence', 'occupation', 'year_salary')],
            ['title' => "生活照", "id" => 6, 'type' => "picture"],
//            ['title' => "坐标", "id" => 2, 'fields' => array('jw_location', 'hometown', 'location', 'work_or_study_place', 'residence')],
            ['title' => "学校", "id" => 4, 'fields' => array('undergraduate', 'master_college', 'current_status', 'education', 'profession')],
//            ['title' => "工作", "id" => 5, 'fields' => array('work_org', 'work_status', 'occupation', 'work_type', 'year_salary')],
            ['title' => "家庭情况", "id" => 8, 'fields' => array('famliy_condition')],
            ['title' => "自我介绍", "id" => 9, 'fields' => array('about_me', 'hobby')],
            ['title' => "心仪的Ta", "id" => 7, 'fields' => array('about_you')],
            ['title' => "实名认证", "id" => 11, 'type' => "picture"],
            ['title' => "本科学历认证", "id" => 10, 'type' => "picture"],
        );
        $extra_ids = array_filter(explode(",", $extra_ids));
        if (count($extra_ids) == 0)
            return $model_set_fields;

        foreach ($model_set_fields as $k => $v) {
            if (in_array($model_set_fields[$k]['id'], $extra_ids)) {
                unset($model_set_fields[$k]);
                continue;
            }
        }

        return $model_set_fields;
    }

    /**
     * 只扣永久爱心
     */
    public function change_account($uid = '', $df_uid = '', $unionid = '', $type = 0, $price = 0, $orderid = '', $inout = 1, $temp_time = '')
    {
        return false;

        if ($uid) {
            $member = Member::where(['id' => $uid])->first();
        } elseif ($unionid) {
            $member = Member::where(['unionid' => $unionid])->first();
        } else {
            return false;
        }
        $member['account'] = str_replace(',', '', $member['account']);
        if ($inout) {// 收入
            $this->updateFields($member['id'], ['account' => bcadd($member['account'], $price, 2)]);
            $add['inout'] = 1;
        } else { //支出
            $this->updateFields($member['id'], ['account' => bcsub($member['account'], $price, 2)]);
            $add['inout'] = 0;
        }
        //记录扣款记录
        $add['unionid'] = $member['unionid'];
        $add['uid'] = $member['id'];
        $add['df_uid'] = $df_uid;
        $add['type'] = $type;//扣款类型
        $add['status'] = 0;
        $add['orderid'] = $orderid;//订单
        $add['amount'] = str_replace(',', '', $price);//金额
        $add['amount_temp'] = 0;
        $add['amount_perm'] = str_replace(',', '', $price);//金额
        $mem_acc = $this->getOne($uid);
        $add['remaining_temp'] = str_replace(',', '', $mem_acc['account_temp']);
        $add['remaining'] = str_replace(',', '', $mem_acc['account']);//账户剩余
        AccountRecord::insert($add);
    }

    /*
    * 增加或扣除账户余额
    * $uid 用户id
    * $price 增加或扣除金额
    * $inout 1:增加账户余额；0：减少账户余额
    */
    public function change_user_account($uid = '', $df_uid = '', $unionid = '', $type = 0, $price = 0, $orderid = null, $inout = 1, $temp_time = '')
    {
        if ($uid) {
            $member = Member::where('id', "=", $uid)->first();
        } elseif ($unionid) {
            $member = Member::where(['unionid' => $unionid])->first();
        } else {
            return false;
        }

        $member['account'] = str_replace(',', '', $member['account']);
        if ($inout) {
            if ($type != 36) {
                if ($temp_time) {
                    $this->updateFields($member['id'], ['account_temp' => bcadd($member['account_temp'], $price, 2)]);
                } else {
                    $this->updateFields($member['id'], ['account' => bcadd($member['account'], $price, 2)]);
                }
            }
            $add['inout'] = 1;//账户增加
        } else {
            $diff = bcsub($member['account_temp'], $price, 2);
            $temp_price = $diff < 0 ? $member['account_temp'] : $price;//扣除了多少限时爱心
            $temp_price && $this->updateFields($member['id'], ['account_temp' => bcsub($member['account_temp'], $temp_price, 2)]);
            if ($temp_price > 0 && $type != 35) {//如果扣除了临时爱心，则循环改变奖励的爱心状态
                //所有有效的限时爱心记录
                $temp_account_list = AccountRecord::where(['uid' => $member['id'], 'status' => 1])->orderby('id', "asc")->select();
                $i = $temp_price;
                foreach ($temp_account_list as $kkk => $vvv) {
                    AccountRecord::where(['id' => $vvv['id']])->update(['status' => 2]);
                    $i = bcsub($i, $vvv['amount'], 2);

                    if ($i == 0) break;
                    if ($i < 0) {
                        $this->change_user_account($member['id'], '', '', 36, abs($i), '', 1, $vvv['temp_time']);
                        break;
                    }
                }
            }

            //如果临时爱心不足，扣除永久爱心
            if ($diff < 0) {
                $this->updateFields($member['id'], ['account' => bcsub(str_replace(',', '', $member['account']), abs($diff), 2)]);
            }

            $add['inout'] = 0;//账户减少
        }

        //记录扣款记录
        $add['unionid'] = $member['unionid'];
        $add['uid'] = $member['id'];
        $add['df_uid'] = $df_uid;
        $add['type'] = $type;//扣款类型
        $add['status'] = $temp_time && $inout ? 1 : 0;
        $add['order_id'] = $orderid ?? null;//订单
        $add['amount'] = str_replace(",", "", $price);//金额
        if (!$inout) {
            $add['amount_temp'] = floatval(str_replace(",", "", $temp_price));
            $add['amount_perm'] = $diff < 0 ? abs($diff) : 0;
        }
        $mem_acc = $this->getOne($uid);
        $add['remaining_temp'] = $mem_acc['account_temp'];
        $add['remaining'] = str_replace(",", "", $mem_acc['account']);//账户剩余
        $temp_time && $add['temp_time'] = $temp_time;//金额

        AccountRecord::insert($add);

        // 判断是否有邀请的
        $this->award_mini_share($uid, $type);
    }

    public function check_member_profile($is_need_realname = false, $is_need_edu = false)
    {
        $wechat_admin_id = request()->get("wechat_admin_id");
        $result['is_all'] = 1;//默认1资料完善
        $result['type'] = array();

        $member = $this->getOne($wechat_admin_id);

        //1-基本信息
        if (empty($member['username'])) {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请填写昵称";
        }

        if (empty($member['gender']) || $member['gender'] == 'U') {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请选择性别";
        }

        if (empty($member['birthday']) || $member['birthday'] == '0000-00' || is_str_has($member['birthday'], '-00')) {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请填写出生年月";
        }

        if (empty($member['height'])) {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请填写身高";
        }

        if (empty($member['marital_history'])) {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请选择婚史";
        }

        /* if (empty($member['ismyself'])) {
             $result['is_all'] = 0;
             $result['type'][] = 1;
             $result['msg'][] = "请选择是否本人";
         }*/

        if (empty($member['make_friend_type'])) {
            $result['is_all'] = 0;
            $result['type'][] = 1;
            $result['msg'][] = "请选择交友类型";
        }

        //2-坐标
        if (empty($member['hometown'])) {
            $result['is_all'] = 0;
            $result['type'][] = 2;
            $result['msg'][] = "请填写家乡";
        }

        if (empty($member['location'])) {
            $result['is_all'] = 0;
            $result['type'][] = 2;
            $result['msg'][] = "请填写现居城市";
        }

        if (empty($member['work_or_study_place'])) {
            $result['is_all'] = 0;
            $result['type'][] = 2;
            $result['msg'][] = "请填写上班地点（在校生填无）";
        }

        if (empty($member['residence'])) {
            $result['is_all'] = 0;
            $result['type'][] = 2;
            $result['msg'][] = "请填写居住地点";
        }

        //3-联系方式  mobile
        if (empty($member['weixin'])) {
            $result['is_all'] = 0;
            $result['type'][] = 3;
            $result['msg'][] = "请填写微信号";
        }

        /*
        $url = env("IMG_DOMAIN") . $member['weixin_qrcode_pic'];
        $qr_result = cos_check_qrcode($member['weixin_qrcode_pic']);
        if (empty($member['weixin_qrcode_pic']) || !($qr_result && is_str_has($qr_result,'https://u.wechat.com'))) {
            $result['is_all'] = 0;
            $result['type'][] = 3;
            $result['msg'][] = "请上传微信二维码";
            if ($qr_result && !is_str_has($qr_result,'https://u.wechat.com')) {
                M('Member')->where('id='.UID)->setField('weixin_qrcode_pic','');
            }
        }
        $qr_result = cos_check_qrcode($member['weixin_qrcode_pic']);
        */

        if (empty($member['weixin_qrcode_pic']) && intval($member['enable_wx_qrcode']) != 1) {
            $qr_result = cos_check_qrcode($member['weixin_qrcode_pic']);

            if (!$qr_result) {
                $result['is_all'] = 0;
                $result['type'][] = 3;
                $result['msg'][] = "请上传微信二维码";
            }

        }

        //4-学校
        if (empty($member['undergraduate'])) {
            $result['is_all'] = 0;
            $result['type'][] = 4;
            $result['msg'][] = "请写本科学校";
        }
        if (empty($member['current_status'])) {
            $result['is_all'] = 0;
            $result['type'][] = 4;
            $result['msg'][] = "请填写目前状态";
        }
        if (empty($member['education'])) {
            $result['is_all'] = 0;
            $result['type'][] = 4;
            $result['msg'][] = "请填写最高学历";
        }
        if (empty($member['profession'])) {
            $result['is_all'] = 0;
            $result['type'][] = 4;
            $result['msg'][] = "请填写专业";
        }
        //5-工作
        if (empty($member['work_org'])) {
            $result['is_all'] = 0;
            $result['type'][] = 5;
            $result['msg'][] = "请填写工作单位（在校生填无）";
        }
        if (empty($member['work_status'])) {
            $result['is_all'] = 0;
            $result['type'][] = 5;
            $result['msg'][] = "请填写工作状况";
        }
        if (empty($member['occupation'])) {
            $result['is_all'] = 0;
            $result['type'][] = 5;
            $result['msg'][] = "请填写职业";
        }

        if (empty($member['work_type'])) {
            $result['is_all'] = 0;
            $result['type'][] = 5;
            $result['msg'][] = "请填写单位类型";
        }

        if (empty($member['year_salary'])) {
            $result['is_all'] = 0;
            $result['type'][] = 5;
            $result['msg'][] = "请填写年收入";
        }

        //8-住房/家庭情况
        /*        if (empty($member['goufang_condition'])) {
                    $result['is_all'] = 0;
                    $result['type'][] = 8;
                    $result['msg'][] = "请填写住房情况";
                }*/

        if (empty($member['famliy_condition'])) {
            $result['is_all'] = 0;
            $result['type'][] = 8;
            $result['msg'][] = "请填写家庭情况";
        }

        //9-想说的话
        if (empty($member['about_me']) || mb_strlen($member['about_me']) < 20) {
            $result['is_all'] = 0;
            $result['type'][] = 9;
            $result['msg'][] = "请填写自我介绍，不少于20字。少于20个字，此提醒将重复出现！";
        }

        /*if (empty($member['hobby']) || mb_strlen($member['hobby']) < 20) {
            $result['is_all'] = 0;
            $result['type'][] = 9;
            $result['msg'][] = "请填写自我介绍，不少于20字。少于20个字，此提醒将重复出现！";
        }*/

        if (empty($member['about_you']) || mb_strlen($member['about_you']) < 15) {
            $result['is_all'] = 0;
            $result['type'][] = 7;
            $result['msg'][] = "请填写心仪的Ta，不少于15字。少于15个字，此提醒将重复出现！";
        }

        //12-更新头像
        if (empty($member['avatar']) || isWxAvatar($member["avatar"], $member['avatar_status'])) {
            $result['is_all'] = 0;//资料不完善
            $result['type'][] = 12;//头像不完善
            $result['msg'][] = "请上传本人真实头像";
        }

        //6-个人相册
        // $member['pictures'] &&
        if (isset($member['pictures']) && count($member['pictures']) < 2) {
            $result['is_all'] = 0;
            $result['type'][] = 6;
            $result['msg'][] = "请上传至少2张本人生活照";
        }

        // dd($result);
        if (empty($member['mobile'])) {
            $result['is_all'] = 0;
            $result['type'][] = 99;//手机号不完善
            $result['msg'][] = "请验证手机号";
        }

        //7-实名认证
        //idcard_status : 0-未提交审核; 4-已提交待审核; 1-审核通过; 2-须重新提交审核; 3-审核不通过;
        if ($is_need_realname && isset($member['idcard_status']) && in_array($member['idcard_status'], [0, 2])) {
            $result['is_all'] = 0;
            $result['type'][] = 7;
            $result['msg'][] = "请完成实名认证";
        }

        //10-本科学历认证
        if ($is_need_edu && isset($member['status']) && in_array($member['status'], [0, 2])) {
            $result['is_all'] = 0;
            $result['type'][] = 10;
            $result['msg'][] = "请完成学历认证";
        }

        //删除type重复数据
        $result['type'] = array_unique($result['type']);
        $result['type'] = array_values($result['type']);

        return $result;
    }

    /*
    * 判断用户账户余额
    * 返回 true    需要充值
    * 返回 false 不需要充值
    */
    public function check_account_balance($uid = 0, $price = 0)
    {
        if (empty($uid)) return;
        $member = Member::where("id", "=", $uid)->first(['account', 'account_temp']);

        if ($member) {
            if ($price) {
                return math_add(str_replace(',', '', $member['account']), $member['account_temp']) >= $price ? false : true;
            } else {
                return math_add(str_replace(',', '', $member['account']), $member['account_temp']) >= 0 ? false : true;
            }
        }
    }

    public function get_account($uid)
    {
        if (!$uid) return false;

        $account = Member::where(function ($q) use ($uid) {
            $q->where("id", "=", $uid)
                ->orWhere("unionid", "=", $uid);
        })->value("account");

        if (isset($account)) {
            return str_replace(',', '', $account);
        } else {
            return 0;
        }
    }

    public function profile_reward($type = '', $member = [])
    {
        if (empty($type)) return;
        $data = new_task_list($type);
        $price = $data['price'];
        switch ($type) {
            case 12://头像
                $new_type = 24;
                break;
            case 6://生活照
                $new_type = 25;
                break;
            case 1://基本信息
                if (empty($member['username']) || empty($member['gender']) || $member['gender'] == 'U' || empty($member['birthday']) || $member['birthday'] == '0000-00' || empty($member['height']) || empty($member['marital_history']) || empty($member['ismyself']) || empty($member['make_friend_type'])) {
                    $new_type = 26;
                }
                break;
            case 2://坐标
                if (empty($member['hometown']) || empty($member['location']) || empty($member['work_or_study_place']) || empty($member['residence'])) {
                    $new_type = 27;
                }
                break;
            case 3://联系方式
                /*  if (empty($member['weixin']) || empty($member['weixin_qrcode_pic'])){
                      $new_type = 28;
                  }*/
                break;
            case 4://学校
                if (empty($member['undergraduate']) || empty($member['current_status']) || empty($member['education']) || empty($member['profession'])) {
                    $new_type = 29;
                }
                break;
            case 5://工作
                if (empty($member['work_org']) || empty($member['work_status']) || empty($member['occupation']) || empty($member['work_type']) || empty($member['year_salary'])) {
                    $new_type = 30;
                }
                break;
            case 8://住房/家庭情况
//                empty($member['goufang_condition']) ||
                if (empty($member['famliy_condition'])) {
                    $new_type = 31;
                }
                break;
            case 9://想说的话
                if (empty($member['about_me']) || empty($member['about_you'])) {
                    $new_type = 32;
                }
                break;
            default:
                break;
        }

        if ($new_type && AccountRecord::where(['type' => $new_type, 'uid' => $member['id']])->count() == 0) {
            $this->change_user_account($member['id'], null, null, $new_type, $price, null, 1, nextMonday());
            return $price;
        }

        return true;
    }

    /**
     * 分享奖励
     * @Author   thomashtao  bosslen
     * @DateTime 2022-04-30T17:05:09+0800
     */
    public function award_mini_share($uid = '', $type = 0, $inout = 1)
    {

        if (!$type) return "";

        $recommend = MemberRecommend::where("uid", "=", $uid)->whereIn("from", ['h5', 'weapp'])->first();
        if (!$recommend) return "";

        //邀请黑名单用户
        $black_list = MemberRecommendBlack::where('id', ">", 0)->pluck('uid')->toArray();
        if (in_array($recommend['ruid'], $black_list)) return "";

        $recommend_member = Member::where("id", "=", $recommend['ruid'])->first(['id', 'is_open_group', 'balance', 'reg_spread_balance']);

        $type_prices = [
            41 => 0.5,     //授权注册奖励1爱心
            22 => 6,     //完成实名认证邀请人奖励6爱心
        ];
        if (empty($type_prices[$type])) return NULL;

        //如果开团后就不奖励爱心 + 奖励金额
        if ($recommend_member['is_open_group'] == 1 || $recommend['award_type'] == 1) {
            // 已经奖励的不再奖励
            if (Income::where(['uid' => $recommend_member['id'], 'type' => 1, 'object_id' => $uid, 'object_type' => "spread"])->count("id"))
                return true;

            $award_price = $recommend_member['reg_spread_balance'];
            $rm_data['balance'] = bcadd($recommend_member['balance'], $award_price, 2);
            $rm_data['total_award'] = bcadd($recommend_member['total_award'], $award_price, 2);  //总收益

            $this->updateFields($recommend_member['id'], $rm_data);

            //增加奖励记录
            $in_data['price'] = $award_price;
            $in_data['uid'] = $recommend_member['id'];
            $in_data['type'] = 1;
            $in_data['object_id'] = $uid;
            $in_data['object_type'] = "spread";
            $in_data['create_time'] = date("Y-m-d H:i:s");

            Income::insert($in_data);
            return true;
        }

        if (intval($recommend['award_type']) == 1) { // 只奖励现金
            return true;
        }
        if (AccountRecord::where(['type' => $type, 'uid' => $recommend['ruid'], 'df_uid' => $uid])->count("id"))
            return NULL;

        $total_price = floatval($type_prices[$type]);
        if ($type == 22) {
            $real_name_num = MemberRecommend::from("member_recommend as mmr")
                ->leftJoin("member as m", "m.id", "=", 'mmr.uid')
                ->where("mmr.ruid", "=", $recommend['ruid'])
                ->where("m.idcard_status", "=", 1)
                ->count('m.id');
            $total_price = $this->_get_real_name_reward($real_name_num);//实名认证给邀请人奖励金额

            $type = 43;//实名认证奖励type是22，下面这个奖励是给邀请人的，描述有变化，故type变更为43
        }

        $member = Member::where("id", "=", $recommend['ruid'])->first();
        $member['account'] = str_replace(',', '', $member['account']);
        //增加微信通知模版 生成应征信息
        sendTemplateMsg($member['openid'], 22, [
            'object_id' => $recommend['id'],
            'object_type' => 'invite_new_user',
            'wo_uid' => $recommend['ruid'],
            'content' => $type == 43 ? "邀请的新用户完成实名认证奖励：" . $type_prices[22] . "永久爱心，当前" . bcadd($member['account'], $type_prices[22]) . "永久爱心" : "邀请的新用户登录小程序奖励" . $type_prices[$type] . "永久爱心，当前" . bcadd($member['account'], $type_prices[$type]) . "永久爱心",
            'amount' => $type_prices[$type],
            'text' => $type == 43 ? "邀请的新用户完成实名认证奖励：" . $type_prices[22] . "永久爱心，当前" . bcadd($member['account'], $type_prices[22]) . "永久爱心" : "邀请的新用户登录小程序奖励" . $type_prices[$type] . "永久爱心，当前" . bcadd($member['account'], $type_prices[$type]) . "永久爱心",
            'page' => "share/content"
        ], 14);

        $this->change_user_account($recommend['ruid'], $uid, null, $type, $total_price, null, $inout);
        return true;
    }

    /**
     * @Author      TomJent
     * @Date        2022-05-31
     * @DateTime    2022-05-31T18:03:26+0800
     * @Description [根据邀请的实名数量，返回奖励爱心数量]
     * @param       [type]
     * @return      [type]
     */
    private function _get_real_name_reward($real_name_num)
    {
        if ($real_name_num == 0) {
            return 0;
        }

        if ($real_name_num == 1) {
            return 6;
        } elseif ($real_name_num >= 2 && $real_name_num <= 3) {
            return 8;
        } elseif ($real_name_num >= 4 && $real_name_num <= 7) {
            return 10;
        } elseif ($real_name_num >= 8 && $real_name_num <= 11) {
            return 12;
        } elseif ($real_name_num >= 12 && $real_name_num <= 15) {
            return 14;
        } elseif ($real_name_num >= 16 && $real_name_num <= 24) {
            return 16;
        } elseif ($real_name_num >= 25) {
            return 18;
        }
    }

    /**
     * 我的统计
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-08T19:31:59+0800
     * @return   [type]                   [description]
     */
    public function getMyStat()
    {
        $enlist_amount = Enlist::where(['enlist_uid' => UID])->count("id");
        $enlisted_amount = Enlist::where(['enlisted_uid' => UID])->count("id");
        $member = Member::where("id", UID)->first(['account', 'account_temp']);
        $total_price = bcadd($member['account'], $member['account_temp'], 2);
        //访客
        $visit_amount = MemberVisit::where(["df_uid" => UID])->count("id");

        return compact("enlist_amount", 'enlisted_amount', 'total_price', 'visit_amount');
    }

    public function getPages($filter = [], int $pageSize = 10, int $pageNum = 1, $order = [], $extra_condtion = [])
    {
        //根据参数计算 cache_key
        $temp_str = json_encode($filter) . $pageNum . $pageSize . $order;
        $cache_key = md5($temp_str);
        $expire_time = 300; //缓存过期时间60秒

        //如果缓存存在直接返回缓存中的数据
        $cache = Cache::get($cache_key);
        $value = Config::where("key", "=", 'cache_invalid_time_stamp')->value("value");
        if ($value - time() >= 0 && $cache) {
            // return $cache ;
        }
        if (!$filter) $filter = array();
        if (!$order) {
            $order['m.last_login_time'] = "desc";
        }

        $fields = [
            1 => ['m.id', "m.username", "m.avatar", "m.total_award", "m.account", "m.account_temp", "m.balance"], //排行版
            2 => ['m.id', "m.username", "m.avatar", "m.account", "m.account_temp", 'm.birthday', 'm.location', 'm.hometown', 'm.height', 'm.work_type', 'm.work_org', 'm.marital_history', 'm.undergraduate', 'm.master_college', 'm.occupation', 'm.status', 'm.idcard_status', 'm.avatar_status', 'm.lcity', 'm.ldistrict', 'm.last_login_time']
        ];

        $filter['m.cancel'] = 1;
        $statuses = "";

        $res = Member::from("member as m")
            ->when(isset($extra_condtion['_string']), function ($q) use ($extra_condtion) {
                return $q->whereRaw($extra_condtion['_string']);
            })
            ->when(!empty($extra_condtion['not_null']), function ($q) use ($extra_condtion) {
                $not_null = array_filter(explode(",", $extra_condtion['not_null']));
                foreach ($not_null as $k => $v) {
                    $q->where($v, '!=', '');
                }
            })
            ->when(!empty($extra_condtion['last_login_time']), function ($q) use ($extra_condtion) {
                return $q->where("m.last_login_time", $extra_condtion['last_login_time'][0], $extra_condtion['last_login_time'][1]);
            })
            ->when(!empty($statuses), function ($q) use ($statuses) {
                if (is_array($statuses)) {
                    return $q->where("m.status", $statuses[0], $statuses[1]);
                } else {
                    return $q->where("m.status", "=", $statuses);
                }
            })
            ->when(!empty($extra_condtion['like_str']), function ($q) use ($extra_condtion) {
                $like_str = array_filter(explode("|", $extra_condtion['like_str'][0]));
                $str = [];
                foreach ($like_str as $k => $v) {
                    $str[] = $v . " like  '%" . $extra_condtion['like_str'][1] . "%'";
                }
                return $q->whereRaw(' ( ' . implode(" or ", $str) . ' ) ');
            })
            ->when(!empty($extra_condtion['like']), function ($q) use ($extra_condtion) {
                if (is_array($extra_condtion['like'])) {
                    foreach ($extra_condtion['like'] as $k => $v) {
                        $q->where($k, "like", "%" . $v . "%");
                    }
                }
            })
            ->when(!empty($extra_condtion['not_in']), function ($q) use ($extra_condtion) {
                foreach ($extra_condtion['not_in'] as $k => $v) {
                    $q->whereNotIn($k, $v);
                }
            })
            ->when(!empty($extra_condtion['in']), function ($q) use ($extra_condtion) {
                foreach ($extra_condtion['in'] as $k => $v) {
                    $q->whereIn($k, $v);
                }
            })
            ->when(!empty($extra_condtion['between']), function ($q) use ($extra_condtion) {
                foreach ($extra_condtion['between'] as $k => $v) {
                    $q->whereBetween($k, $v);
                }
            })
            ->when(isset($order), function ($q) use ($order) {
                if (is_array($order)) {
                    foreach ($order as $k => $o) {
                        $q->orderBy($k, $o);
                    }
                }
            })
            ->where($filter)
            ->paginate($pageSize, $fields[$extra_condtion['field']] ?? "m.*", null, $pageNum)
            ->toArray();

        // exit();
        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => $v) {
            $v['pictures'] = (new PictureMappingRepository())->getMappingBySearch(['object_type' => "member", 'object_id' => $v['id']], true);
            $res['items'][$k] = $v;
        }

        return $res;
    }

    /**
     * $param 可以传入member对象 或者用户id
     */
    public function get_user_desc($param)
    {
        if (is_array($param))
            $member = $param;
        else if (is_numeric($param))
            $member = $this->getOne($param);

        $arr = array("省", "市");
        return member_gender($member['gender']) . "，" . substr($member['birthday'], 2, 2) . "年，" . $member['height'] . "，" . str_replace($arr, '', str_replace(' ', '', $member['hometown'])) . "人，坐标" . $member['residence'] . "，" . $member['occupation'];
    }

    /**
     * $code 学信网验证码
     * $realname 姓名
     */
    public function checkChsiCode($params, $uid = null)
    {
        $url = "https://www.chsi.com.cn/xlcx/bg.do?vcode=" . $params['education_number'] . "&srcid=bgcx";
        $realname = Member::where("id", "=", $uid)->value("realname");

        $headers = randIp();
        $content = curlHelper($url, 'GET', [], $headers)['body'];
        $content = preg_replace("/[\t\n\r]+/", "", $content);

        preg_match_all('/<h4>(.*?)<\/h4>/i', $content, $res);
        $chsi_title = $res[1][0];//当前认证类型：学籍、学历、还是学位

        if (!in_array($chsi_title, ['教育部学籍在线验证报告', '教育部学历证书电子注册备案表'])) {
            return retFail("请提交本科【学籍】、【学历】验证码，不审核【学位】");
        }

        // ==============获取图片begin
        $content = str_replace("/report/img/", "https://www.chsi.com.cn/report/img/", $content);
        $start = '<div id="resultTable">';  //开始的内容
        $end = '<div class="foot-wrap" id="footer">';         //结束的内容
        $wzs = strpos($content, $start);              //开始的位置
        $wze = strpos($content, $end);                    //结束的位置
        $len = $wze - $wzs;                     //内容的总长度
        $content = substr($content, $wzs, $len);      //目的：只显示我们需要的那一部分
        $css = '<html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>教育部学籍在线验证报告_中国高等教育学生信息网（学信网）</title>
        <meta name="keywords" content="教育部学籍在线验证报告,学历在线验证报告,教育部学历证书电子注册备案表,学历查询,学历验证,学信网" />
        <meta name="description" content="" />
        <link href="https://weapp.bsbly.com/styles/zxyz_bg.css" rel="stylesheet" type="text/css">';
        $content = $css . $content;
        file_put_contents($params['education_number'] . ".html", $content);
        $json = $this->send_post($params['education_number'], $content);
        unlink($params['education_number'] . ".html");//删除
        $image = json_decode($json, true);
        $image = $image["data"]["image"]; // =============获取图片end

        $edu_path = base64_to_jpeg($image, 'edu_' . $uid);
//        $path = (new FileRepository())->uploadFileToCos($edu_path);

        $update['education_pic'] = $edu_path;
        $update['education_type'] = $params['education_type'];
        $update['education_number'] = $params['education_number'];
        $update['is_checker'] = 1;

        $pattern = '/<div class="report-info-item">.*?<div class="label">(.*?)<\/div>.*?<div class=".*?">(.*?)<\/div>.*?<\/div>/i';
        preg_match_all($pattern, $content, $matches);

        $begin_time = '';
        $end_time = '';

        for ($i = 0; $i < substr_count($content, "report-info-item"); $i++) {
            $label = trim($matches[1][$i]);
            $value_long = trim($matches[2][$i]);

            // 检查姓名是否一致
            if ($label == '姓名' && $value_long != trim($realname)) {
                return retFail("实名认证姓名和学历姓名不一致，请勿使用他人信息认证");
            }

            if ($chsi_title == '教育部学历证书电子注册备案表') {
                if (in_array($label, ['学校名称', '院校'])) {
                    $update['undergraduate'] = $value_long;
                }
                if ($label == '层次' && $value_long != '本科') {// TODO 专科 直接审核不通过；为硕博，提示重新上传本科学籍学历验证码
                    if ($value_long == '专科') {
                        //审核不通过
                        $update['status'] = 3;
                        $this->saveOrUpdate($update, $uid);
                        $this->addChsiCheckRecord($uid, 3);
                        return retSuc([], "审核完成");
                    } else {//硕博
                        return retFail("提交本科【学籍】、【学历】验证码, 不审核硕博学籍、学历");
                    }
                }
                if ($label == '学历类别' && $value_long != '普通高等教育') {
                    //审核不通过
                    $update['status'] = 3;
                    $this->saveOrUpdate($update, $uid);
                    $this->addChsiCheckRecord($uid, 3);
                    return retSuc([], "审核完成");
                }
                if ($label == '学习形式' && !in_array($value_long, ['全日制', '普通全日制'])) {
                    //审核不通过
                    $update['status'] = 3;
                    $this->saveOrUpdate($update, $uid);
                    $this->addChsiCheckRecord($uid, 3);
                    return retSuc([], "审核完成");
                }

                if ($label == '入学日期') {
                    $begin_time = $value_long;
                }
                if ($label == '毕（结）业日期') {
                    $end_time = $value_long;
                }
            }

            if ($chsi_title == '教育部学籍在线验证报告') {
                if (in_array($label, ['学校名称', '院校'])) {
                    $update['undergraduate'] = $value_long;
                }
                if ($label == '层次' && $value_long != '本科') {// TODO 专科 直接审核不通过；为硕博，提示重新上传本科学籍学历验证码
                    if ($value_long == '专科') {
                        //审核不通过
                        $update['status'] = 3;
                        $this->saveOrUpdate($update, $uid);
                        $this->addChsiCheckRecord($uid, 3);
                        return retSuc([], "审核完成");
                    } else {//硕博
                        return retFail("提交本科【学籍】、【学历】验证码,不审核硕博学籍、学历");
                    }
                }

                if ($label == '类型' && $value_long != '普通高等教育') {
                    //审核不通过
                    $update['status'] = 3;
                    $this->saveOrUpdate($update, $uid);
                    $this->addChsiCheckRecord($uid, 3);
                    return retSuc([], "审核完成");
                }
                if ($label == '形式' && !in_array($value_long, ['全日制', '普通全日制'])) {
                    //审核不通过
                    $update['status'] = 3;
                    $this->saveOrUpdate($update, $uid);
                    $this->addChsiCheckRecord($uid, 3);
                    return retSuc([], "审核完成");
                }
                if ($label == '入学日期') {
                    $begin_time = $value_long;
                }
                if ($label == '学籍状态') {
                    $end_time = $this->handle_time_str($value_long);
                    if (empty($end_time)) {
                        // 转人工审核
                        return retFail("解析异常");
                    }
                }
            }

        }

        if ($this->checkYear($begin_time, $end_time)) {
            //审核不通过
            $update['status'] = 3;
            $this->saveOrUpdate($update, $uid);
            $this->addChsiCheckRecord($uid, 3);
            return retSuc([], "审核完成");
        }

        $count = AccountRecord::where(['uid' => $uid, 'type' => 23])->count();
        if ($count == 0) {
            // 实名认证奖励
            $this->change_user_account($uid, NULL, "", 23, get_new_task_price(10), NULL, 1, nextMonday());
        }
        $update['status'] = 1;
        $this->saveOrUpdate($update, $uid);
        $this->addChsiCheckRecord($uid, 1);

        return retSuc([], "恭喜，完成本科学历认证！");
    }

    function https_request($url, $data)
    {
        $curl = curl_init();
        $headers = [
            'Content-Type: application/json;charset=utf-8',
            'Authorization: 1234qwer',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_HEADER, false);
        //是否打印服务器返回的header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //要求结果为字符串且输出到屏幕上
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    // 记录系统自动审核记录
    private function addChsiCheckRecord($uid, $status)
    {
        $data['uid'] = $uid;
        $data['status'] = $status;
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['update_time'] = date('Y-m-d H:i:s');

        ChsiCheck::create($data);
    }

    private function handle_time_str($str)
    {
        $arr = explode("：", str_replace(['（', '）'], '', $str));
        return $arr[1];
    }

    //判断入学、毕业时间是否大于等于4年
    private function checkYear($year1, $year2)
    {
        $diff = intval(substr($year2, 0, 4)) - intval(substr($year1, 0, 4));
        if ($diff < 4) {
            return true;
        }
        return false;
    }

    function send_post($code, $html)
    {
        $html = preg_replace("/[\t\n\r]+/", "", $html);
        $html = addslashes($html);
        $info = "{
              \"pageUrl\":\"\",
              \"html\" : \"$html\",
              \"element\":\"body\",
              \"timeout\": 30000,
              \"checkPageCompleteJs\": \"document.readyState === 'complete'\",
              \"delay\": 100,
              \"width\": 780,
              \"height\": 1108
          }";

        // 172.17.0.2
        $json = json_decode($this->https_request("http://152.136.139.129:3000/api/img", $info), true);
        $return = json_encode($json, JSON_UNESCAPED_UNICODE);
        return $return;
    }

    /**
     * 基本信息
     */
    public function checkBaseProfile($member = null)
    {
        if (empty($member)) {
            $member = $this->getOne(UID);
        }

        if (empty($member['birthday'])) {
            return false;
        }

        if (empty($member['height'])) {
            return false;
        }

        return true;
    }

}
